package in.muton.edushare.components.calendar.api;

import in.muton.edushare.EduShareSession;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.edushare.common.dao.UsersDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.ScheduleNotifications;
import com.edushare.common.vo.Schedules;
import com.edushare.common.vo.Users;

public class PeopleManager {
	
	public static String cleanConvert(String s){
		if(!StringUtil.isValid(s))
			return "";
		Pattern p = Pattern.compile(";+");
		s = s.replace(' ', ';').replace(',', ';').replace('\n',
				';').replace('\r', ';');
		Matcher m = p.matcher(s);
		String userNames[] =  m.replaceAll(";").split(";");
		UsersDAO userDAO = new UsersDAO(EduShareSession.get().getSessionORMInterface());
		for(String name:userNames){
			Users vo = userDAO.getUserByUserNameOrEmail(name);
			if(vo == null)
				return "Unable to find user with user name "+ name;
		}
		return "";
	}
	
	public static List<Users> getUsers(String s) {
		if(!StringUtil.isValid(s))
			return new ArrayList<Users>();
		Pattern p = Pattern.compile(";+");
		s = s.replace(' ', ';').replace(',', ';').replace('\n',
				';').replace('\r', ';');
		Matcher m = p.matcher(s);
		String userNames[] =  m.replaceAll(";").split(";");
		UsersDAO userDAO = new UsersDAO(EduShareSession.get().getSessionORMInterface());
		List<Users> userList = new ArrayList<Users>();
		for(String name:userNames){
			Users vo = userDAO.getUserByUserNameOrEmail(name);
			if(vo != null){
				userList.add(vo);
			}
		}
		return userList;
	}

	public static String getProperList(Schedules sch, int max, int status) {
		List<ScheduleNotifications> snL = sch.getNotifiedUsers();
		String s = "";
		int cnt = 0;
		for(ScheduleNotifications sn:snL){
			if(status ==0 || sn.getActionStatus() == status){
				if(s.length() !=0)
					s += ", ";
				s += sn.getUser().getCompleteUserName();
				cnt++;
				if(cnt >= max)
					break;
			}
		}
		if(snL.size() > max)
			return s + " and " + (snL.size() - max) + "others.";
		else
			return s;
	}
	
	public static int getInviteeCount(Schedules sch, int status){
		List<ScheduleNotifications> shL = sch.getNotifiedUsers();
		int count = 0;
		for(ScheduleNotifications s:shL){
			if(s.getActionStatus() == status)
				count ++;
		}
		return count;
	}

	public static String getEmailList(Schedules sch) {
		List<ScheduleNotifications> snL = sch.getNotifiedUsers();
		String s = "";
		for(ScheduleNotifications sn:snL){
			s += sn.getUser().getEmail() +";";
		}
		return s;
	}
	
}
